<template>
  <div>
    <!-- 菜单 -->
    <el-form :inline="true" class="demo-form-inline" label-width="auto" size="mini">
      <el-form-item label="角色名称">
        <el-input v-model="roleInfo.roleName" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item label="状态：">
        <el-select v-model="roleInfo.status" clearable placeholder="请选择">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="btn-set" icon="el-icon-search" @click="query">
          查询
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" class="btn-set" icon="el-icon-plus" @click="add">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="danger" class="btn-set" icon="el-icon-delete" @click="delList">
          删除
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 角色列表 -->
    <el-table
      border
      :data="roleList"
      style="width: 100%"
      size="mini"
      :cell-style="{ 'text-align': 'center' }"
      :header-cell-style="{ 'text-align': 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column fixed prop="roleId" label="序号" width="70" resizable></el-table-column>
      <el-table-column prop="roleSet" label="角色编码" width="120"></el-table-column>
      <el-table-column prop="roleName" label="角色名称" width="180"></el-table-column>
      <el-table-column prop="effectTime" label="生效时间" width="auto">
        <template slot-scope="{ row }">
          {{ row.effectTime ? row.effectTime.split(' ')[0] : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="uneffectTime" label="失效时间" width="auto">
        <template slot-scope="{ row }">
          {{ row.uneffectTime ? row.uneffectTime.split(' ')[0] : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="70">
        <template slot-scope="scope">
          <!-- scope.row 可以取到当前一行的数据 -->
          <!-- {{ scope.row }} -->
          <el-switch v-model="scope.row.status" active-value="1" inactive-value="0"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template slot-scope="scope">
          <el-button
            type="warning"
            size="mini"
            :disabled="scope.row.roleId === 1"
            @click="edit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            size="mini"
            :disabled="scope.row.roleId === 1"
            @click="del(scope.row)"
          >
            删除
          </el-button>
          <el-button
            type="primary"
            size="mini"
            :disabled="scope.row.roleId === 1"
            @click="set(scope.row)"
          >
            设置角色权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="roleInfo.pageNo"
        :page-sizes="[10, 15, 20]"
        :page-size="roleInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="count"
      ></el-pagination>
    </div>

    <!-- 新增 编辑角色弹窗 -->
    <el-dialog
      :title="this.roleform.roleId ? '编辑角色' : '新增角色'"
      :visible.sync="dialogRoleVisible"
      width="40%"
      @close="close"
    >
      <el-form :model="roleform" :rules="rules" class="demo-form-inline" ref="roleDialog">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="角色编码:" :label-width="formLabelWidth" prop="roleSet">
              <el-input
                v-model="roleform.roleSet"
                autocomplete="on1"
                class="dialog_ipt"
                :disabled="editRoleList.roleId"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="角色名称:" :label-width="formLabelWidth" prop="roleName">
              <el-input
                v-model="roleform.roleName"
                autocomplete="off"
                class="dialog_ipt"
                placeholder="请输入角色名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="生效日期:" :label-width="formLabelWidth" prop="effectTime">
              <el-date-picker
                v-model="roleform.effectTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="失效日期:" :label-width="formLabelWidth" prop="uneffectTime">
              <el-date-picker
                v-model="roleform.uneffectTime"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd HH:mm:ss"
                :disabled="isChange"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="状态:" :label-width="formLabelWidth">
              <template>
                <el-radio v-model="roleform.status" label="1">有效</el-radio>
                <el-radio v-model="roleform.status" label="0">无效</el-radio>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注:" :label-width="formLabelWidth">
              <el-input
                v-model="roleform.remake"
                type="textarea"
                autocomplete="off"
                class="dialog_ipt"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="btnOk">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 设置角色权限 -->
    <el-dialog title="角色设置" :visible.sync="dialogTableVisible" width="40%" @close="closeMenu">
      <el-form :model="roleform">
        <el-form-item label="用户名:" :label-width="formLabelWidth">
          <el-input
            v-model="roleform.roleName"
            autocomplete="on1"
            class="dialog_ipt"
            :disabled="true"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-tree
        :data="data"
        show-checkbox
        node-key="id"
        ref="tree"
        :default-expanded-keys="[2, 3, 4]"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeMenu">取 消</el-button>
        <el-button type="primary" @click="getCheckedNodes">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Message, MessageBox } from 'element-ui'

import {
  selectroleAPI,
  addRoleAPI,
  deleteRoleAPI,
  editRoleAPI,
  selectIdAPI,
  setRolePowerAPI,
  roleGetOneAPI
} from '../../api/roleAPI'

export default {
  name: 'MyUser',
  data() {
    return {
      // 弹窗数据
      roleform: {
        roleName: '',
        roleSet: '',
        effectTime: '',
        uneffectTime: '',
        status: '1',
        remake: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入您的角色名称', trigger: 'blur' },
          {
            pattern: /^[A-Za-z\u4E00-\u9FA5]{6,20}$/,
            message: '请输入由字母汉字组成且长度6~20位的角色名称',
            trigger: 'blur'
          }
        ]
        // roleSet: [
        //   { required: true, message: '请输入您的角色编码', trigger: 'blur' },
        //   { min: 3, max: 20, message: '请输入长度3~20位的角色编码', trigger: 'blur' }
        // ]
      },
      formLabelWidth: '120px',
      options: [
        {
          value: '1',
          label: '有效'
        },
        {
          value: '0',
          label: '无效'
        }
      ],
      // 查询数据
      roleInfo: {
        roleName: '',
        status: '',
        // 页码数
        pageNo: 1,
        // 展示的数据条数
        pageSize: 10
      },
      count: 1,
      // 用户列表数据
      roleList: [],
      // 编辑角色数据
      editRoleList: {},
      // 新增弹窗开关
      dialogRoleVisible: false,
      // 设置角色权限
      dialogTableVisible: false,
      data: [
        {
          id: 1,
          label: '系统管理',
          children: [
            {
              id: 2,
              label: '用户管理',
              children: [
                {
                  id: 5,
                  label: '查询用户'
                },
                {
                  id: 6,
                  label: '修改用户'
                },
                {
                  id: 7,
                  label: '删除用户'
                },
                {
                  id: 8,
                  label: '新增用户'
                },
                {
                  id: 9,
                  label: '设置角色'
                }
              ]
            },
            {
              id: 3,
              label: '角色管理',
              children: [
                {
                  id: 10,
                  label: '查询角色'
                },
                {
                  id: 11,
                  label: '修改角色'
                },
                {
                  id: 12,
                  label: '删除角色'
                },
                {
                  id: 13,
                  label: '新增角色'
                },
                {
                  id: 14,
                  label: '设置角色权限'
                }
              ]
            },
            {
              id: 4,
              label: '菜单管理',

              children: [
                {
                  id: 15,
                  label: '查询菜单'
                },
                {
                  id: 16,
                  label: '修改菜单'
                },
                {
                  id: 17,
                  label: '删除菜单'
                },
                {
                  id: 18,
                  label: '新增菜单'
                }
              ]
            }
          ]
        }
      ],
      // 全选框勾选的数据
      multipleSelection: [],
      // 是否禁用失效日期
      isChange: true,
      setMenu: {
        roleId: '',
        menuIds: []
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const result = await selectroleAPI(this.roleInfo)
      this.roleList = result.conditionlist
      this.count = result.count
    },

    // 分页数据条数
    handleSizeChange(val) {
      this.roleInfo.pageSize = val
      this.getRoleList()
    },
    // 分页页码
    handleCurrentChange(val) {
      this.roleInfo.pageNo = val
      this.getRoleList()
    },
    // 角色新增事件
    add() {
      this.dialogRoleVisible = true
      this.editRoleList = {}
    },
    // 批量删除
    async delList() {
      const arr = []
      this.multipleSelection.forEach(item => {
        arr.push(item.roleId)
      })
      try {
        await MessageBox.confirm('您确定要删除吗')
        const result = await deleteRoleAPI(arr)
        if (result.code === '1') {
          Message.success('删除成功')
          this.getRoleList()
        } else {
          Message.error('您没有此权限')
        }
      } catch (err) {
        Message('取消删除')
      }
    },
    // 点击编辑事件
    async edit(row) {
      const result = await selectIdAPI({ roleId: row.roleId })
      this.editRoleList = result
      console.log(result)
      this.dialogRoleVisible = true
      this.roleform = JSON.parse(JSON.stringify(row))
    },
    // 查询角色事件
    async query() {
      const result = await selectroleAPI(this.roleInfo)
      this.roleList = result.conditionlist
    },
    // 删除角色事件
    async del(row) {
      try {
        await MessageBox.confirm('您确定要删除吗')
        const result = await deleteRoleAPI([row.roleId])
        if (result.code === '1') {
          Message.success('删除成功')
          this.getRoleList()
        } else {
          Message.error('您没有此权限')
        }
      } catch (err) {
        Message('取消删除')
      }
    },
    // 新增编辑弹窗关闭事件
    close() {
      this.roleform = {}
      this.dialogRoleVisible = false
      this.$refs.roleDialog.resetFields()
    },
    // 设置角色弹窗关闭事件
    closeMenu() {
      this.dialogTableVisible = false
      this.roleform.roleName = ''
    },
    // 弹框确认事件
    btnOk() {
      this.$refs.roleDialog.validate(async val => {
        if (this.editRoleList.roleId) {
          if (val) {
            const result = await editRoleAPI(this.roleform)
            console.log(result)
            if (result.code === '1') {
              this.close()
              Message.success('编辑成功')
              this.getRoleList()
            } else {
              Message.error('您没有此权限')
              this.close()
            }
          }
        }
        // 如果没有id就是新增事件
        else {
          if (val) {
            const result = await roleGetOneAPI(this.roleform.roleName)
            if (result.roleName) {
              Message.error('该角色名称已存在')
              this.close()
            } else {
              try {
                await MessageBox.confirm('您确定要新增吗')
                const result = await addRoleAPI(this.roleform)
                if (result.code === '1') {
                  this.close()
                  Message.success('新增成功')
                  this.getRoleList()
                } else {
                  Message.error('您没有此权限')
                  this.close()
                }
              } catch (err) {
                Message.error('新增失败')
              }
            }
          }
        }
      })
    },
    // 设置权限功能
    async getCheckedNodes() {
      const arr = []
      // this.setMenu.menuIds = this.$refs.tree.getCheckedNodes()
      this.$refs.tree.getCheckedNodes().forEach(item => {
        arr.push(item.id)
      })
      this.setMenu.menuIds = arr
      const result = await setRolePowerAPI(this.setMenu.roleId, this.setMenu.menuIds)
      if (result.code === '1') {
        Message.success('设置权限成功')
        this.closeMenu()
      }
    },
    // 设置角色权限
    set(row) {
      this.dialogTableVisible = true
      this.roleform = JSON.parse(JSON.stringify(row))
      this.setMenu.roleId = row.roleId
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    }
  },
  watch: {
    'roleform.status'(val) {
      if (val === '0') {
        this.isChange = false
        this.roleform.uneffectTime = null
      } else {
        this.isChange = true
      }
    }
  }
}
</script>

<style lang="less" scoped>
.btn-set {
  margin: 0 5px;
}

.el-pagination {
  margin-top: 5px;
  position: absolute;
  left: 50%;
  transform: translate(-50%, 0);
}
.dialog_ipt {
  width: 260px;
}
</style>
